package com.zcsy.manage.web.system;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.system.App;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.system.IAppService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;

/**
 * @Project: manage
 * @Title: AppController
 * @Package com.zcsy.manage.web.system
 * @Description:app版本控制层管理类
 * @author fangli Fanglwj520@163.com
 * @date 2016年5月13日 下午3:10:26
 * @Copyright：2014 武汉恒数利通软件有限公司 All rights reserved.
 * @version 1.0
 */
@Controller
@RequestMapping(value = "/app")
public class AppController {
    
//    private static final int PAGE_SIZE = 5; // 每页大小
    
    @Autowired
    private IAppService appService;

	@Autowired
	private IDictService dictService;
	
    /**
     * @Description APP信息关键字检索
     * @param pNo 当前页码
     * @param versionNo 版本号
     * @param type 类型
     * @param req 用户请求
     * @return 跳转页面URL
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月16日
     * @see 
     */
    @RequestMapping(value = "appList", method = RequestMethod.GET)
    public String getAll(Model model,Integer pNo, Integer pSize, String versionNo,String type){ 
        if (pNo == null) {
            pNo = Constants.PAGE_NO;
        }

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
        // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, pageSize);
        App record = new App();
        // 版本号为不空字符串时，设置版本号
        if (null != versionNo) {
            record.setVersionNo(versionNo);
        }
        if(null != type){
            record.setType(type); 
        }
        List<App> appList = appService.selectApp(record);
        PageInfo<App> Info = new PageInfo<App>(appList);
        model.addAttribute("appList",appList);
        model.addAttribute("appInfo", Info);
        model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
        model.addAttribute("versionNo",versionNo);
        model.addAttribute("type",type);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

        return"system/app/appList";
    }
    /**
     * @Description 编辑信息的保存
     * @param versionNo 版本号
     * @param type 类型
     * @param container 更新内容
     * @param appId 主键id
     * @param response 响应
     * @return 请求结果
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月16日
     * @see 
     */
    @RequestMapping(value = "edit", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson editApp(String versionNo,String type,String container,String appId,String downloadUrl,HttpServletRequest request ,HttpServletResponse response){
        RequestJson result = new RequestJson();
        try {
            App record = new App();
            User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            record.setVersionNo(versionNo);
            record.setType(type);
            record.setUpdateContent(container);
            if(!"0".equals(appId) && appId != null){
                record.setId(appId);
                record.setUploadTime(DateUtils.getFmtDate());
                appService.updateAppInfo(record);
                LogUtils.insertLog("用户编辑客户端信息", user.getId(), request);
            }else{ 
                if(appService.selectAppIfExists(versionNo, type)) {
                    result.setSuccess(false);
                    result.setMsg("版本已存在,请重新输入版本号!");
                    return result; 
                  }
                record.setDownloadUrl(downloadUrl);
                record.setUploadPerson(user.getLoginname());
                record.setUploadTime(DateUtils.getFmtDate());
                record.setId(UniqueNumberUtils.get18UniqueNumber());
                appService.insert(record);
                LogUtils.insertLog("用户新增客户端信息", user.getId(), request);
            }

        }catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增失败!");
        }
        return result;
    }
    /**
     * @Description APP信息编辑
     * 
     * @param id 主键id
     * @return 编辑页面链接
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月16日
     * @see 
     */
    @RequestMapping(value ="update",method = RequestMethod.GET)
    public String  update(Model model,String id) {
        App app = new App();
        if (String.valueOf(Constants.STATE_DISABLED).equals(id)) {
//            model.addAttribute("app", null);
            model.addAttribute("type",Constants.SAVE_TYPE);
        }else {
            app = appService.selectByPrimaryKey(id);
            if(app != null){
                model.addAttribute("type", Constants.EDIT_TYPE);
                model.addAttribute("app", app); 
            }
        }
        
        return "system/app/appEdit";
        
    }
    /**
     * @Description 删除APP信息<br>
     * 
     * @param appIds 多个id
     * @param req 用户请求
     * @return 请求结果
     * @author fangli Fanglwj520@163.com
     * @date 2016年5月16日
     * @see 
     */
    @RequestMapping(value = "delete",method = RequestMethod.GET)
    @ResponseBody
    public RequestJson delete(String appIds,HttpServletRequest req) {

     RequestJson result = new RequestJson();
     User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

     try {
         String ids[] = appIds.split("\\,");
         for (int i = 0; i < ids.length; i++ ) {
             appService.deleteAppInfo(ids[i]);
         }
         result.setSuccess(true);
         LogUtils.insertLog("用户删除客户端信息", user.getId(), req);
     } catch (NumberFormatException e) {
         result.setSuccess(false);
         result.setMsg("操作失败");
     }
     return result;
 }
}
